//
//  KKTiXianVC.m
//  DoMi
//
//  Created by 康凯 on 2016/11/17.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKTiXianVC.h"
#import "KKMyHttp.h"
#import "KKTiXianM.h"
#import "KKUploadDialog.h"
#import <AliyunOSSiOS/OSSService.h>
#import "KKLoginHttp.h"

@interface KKTiXianVC ()<UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *balance;
@property (weak, nonatomic) IBOutlet UITextField *tiXianMoney;
@property (weak, nonatomic) IBOutlet UILabel *sxf;
@property (weak, nonatomic) IBOutlet UILabel *tixianRealMoney;
@property (weak, nonatomic) IBOutlet UITextField *cardBank;
@property (weak, nonatomic) IBOutlet UITextField *cardNum;
@property (weak, nonatomic) IBOutlet UITextField *cardName;
@property (weak, nonatomic) IBOutlet UIImageView *SFZImg;
@property (weak, nonatomic) IBOutlet UIPickerView *bankPicker;
@property (weak, nonatomic) IBOutlet UILabel *bankName;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (strong, nonatomic) OSSClient *client;

@property(copy,nonatomic)NSString *realMoney;
@property(strong,nonatomic)NSArray *bankNames;
@property(copy,nonatomic)NSString *sfzUrl;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (assign,nonatomic) int count;
@property (strong,nonatomic) NSTimer *timer;

@property (weak, nonatomic) IBOutlet UITextField *code;



@property (strong,nonatomic) KKTiXianM *tiXianInfo;

@end

@implementation KKTiXianVC

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.timer invalidate];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    
    [self getTiXianInfo];
}

-(void)initView{
    self.navigationItem.title=@"提现";
    self.tiXianMoney.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    self.cardNum.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    self.cardName.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    self.cardBank.leftView= [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    self.code.leftView= [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0)];
    //设置显示模式为永远显示(默认不显示)
    self.tiXianMoney.leftViewMode = UITextFieldViewModeAlways;
    self.cardNum.leftViewMode = UITextFieldViewModeAlways;
    self.cardName.leftViewMode = UITextFieldViewModeAlways;
    self.cardBank.leftViewMode = UITextFieldViewModeAlways;
    self.code.leftViewMode = UITextFieldViewModeAlways;
    
    self.tiXianMoney.delegate=self;
    
    
    self.bankPicker.delegate=self;
    self.bankPicker.dataSource=self;
    self.bankPicker.showsSelectionIndicator=YES;
    self.bankNames=@[@"中国银行",@"工商银行",@"农业银行",@"民生银行"];
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker=imagePicker;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
    
    id<OSSCredentialProvider> credential=[[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:ACCESSKEY secretKey:SECRETKEY];
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 2;
    conf.timeoutIntervalForRequest = 30;
    conf.timeoutIntervalForResource = 24 * 60 * 60;
    self.client=[[OSSClient alloc] initWithEndpoint:ENDPOINT credentialProvider:credential clientConfiguration:conf];
}
-(void)initData{
    self.balance.text=[NSString stringWithFormat:@"¥%@",self.tiXianInfo.balance];
    float temp=[self.tiXianInfo.sxf floatValue];
    temp=temp*100;
    self.sxf.text=[NSString stringWithFormat:@"温馨提示：平台将收取%.2lf%@的手续费",temp,@"%"];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark imagepicker代理
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]){
        //如果是图片
        UIImage *selectImg= info[UIImagePickerControllerEditedImage];;
        //压缩图片
        NSData *fileData = UIImageJPEGRepresentation(selectImg, 1.0);
        //保存图片至相册
        //        UIImageWriteToSavedPhotosAlbum(selectImg, self,nil, NULL);
        [self uploadObjectAsync:fileData];
        self.SFZImg.hidden=NO;
        [self.SFZImg setImage:selectImg];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark pickerView代理
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return self.bankNames.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return self.bankNames[row];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *msg=[NSString stringWithFormat:@"您选择了%@",self.bankNames[row]];
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.bankName.text=self.bankNames[row];
        self.bankPicker.hidden=YES;
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark textfiled代理
-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    if(![KKAppUtils isEmptyString:textField.text]){
        float tixianMoney=[textField.text floatValue];
        float balance=[self.tiXianInfo.balance intValue];
        if(tixianMoney>balance){
            [self toast:@"提现金额超出总额度"];
            textField.text=@"";
            return;
        }

        float sxf=[self.tiXianInfo.sxf floatValue];
        float real=balance-tixianMoney*sxf;
        self.realMoney=[NSString stringWithFormat:@"%.2f",real];
        self.tixianRealMoney.text=[NSString stringWithFormat:@"%.2f元",real];
    }
}

- (IBAction)codeClick:(id)sender {
    self.count=60;
    [self.codeBtn setEnabled:NO];
    self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(scheduleTimer) userInfo:nil repeats:YES];
    //发送验证码
    NSDictionary *params=@{@"phone":self.tiXianInfo.phone};
    [KKLoginHttp getCode:params success:^(id responseObject) {
        [self toast:@"发送成功"];
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark 倒计时
-(void)scheduleTimer{
    self.count--;
    NSString *time=[NSString stringWithFormat:@"%ds重新获取",self.count];
    [self.codeBtn setTitle:time forState:UIControlStateNormal];
    if(self.count==0){
        [self.timer invalidate];
        [self.codeBtn setEnabled:YES];
        [self.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.count=60;
    }
    
}

#pragma mark 按钮--提现
- (IBAction)updateTiXianBtn:(id)sender {
    float tixianMoney=[self.tiXianMoney.text floatValue];
    float balance=[self.tiXianInfo.balance floatValue];
    
    if([KKAppUtils isEmptyString:self.tiXianMoney.text]){
        [self toast:@"请输入提现金额"];
        return;
    }
    if(tixianMoney>balance){
        [self toast:@"提现金额超出总额度"];
        return;
    }
    
    if([self.cardBank.text isEqualToString:@"请输入开户银行"]){
        [self toast:@"请输入开户银行"];
        return;
    }
    if([KKAppUtils isEmptyString:self.cardNum.text]){
        [self toast:@"请输入卡号"];
        return;
    }
    if([KKAppUtils isEmptyString:self.cardName.text]){
        [self toast:@"请输入持卡人姓名"];
        return;
    }
    if([KKAppUtils isEmptyString:self.code.text]){
        [self toast:@"请先获取验证码"];
        return;
    }

    [self updateTiXian];
}
#pragma mark 按钮--选择银行
-(void)selectBank{
    self.bankPicker.hidden=NO;
}
#pragma mark 按钮--上传身份证
- (IBAction)uploadSFZClick:(id)sender {
    KKUploadDialog *upload=[[[NSBundle mainBundle] loadNibNamed:@"KKUploadDialog" owner:self options:nil] lastObject];
    upload.uploadBlock=^(int flag){
        if(flag==1){
            self.imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        }else if(flag==2){
            self.imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        }
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    };
    [upload show];
}

#pragma mark 接口--oss上传图片
// 异步上传
- (void)uploadObjectAsync:(NSData *)uploadImgData{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    [fmt setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    NSString *ds = [fmt stringFromDate:date];
    
    put.bucketName = BUCKET_NAME;
    put.objectKey = [NSString stringWithFormat:@"%@.jpg",ds];
    put.uploadingData=uploadImgData;
    
    //    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    hud.mode = MBProgressHUDModeDeterminate;
    //    hud.label.text = @"正在上传图片";
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        dispatch_sync(dispatch_get_main_queue(), ^{//其实这个也是在子线程中执行的，只是把它放到了主线程的队列中
            Boolean isMain = [NSThread isMainThread];
            if (isMain) {
                [SVProgressHUD showProgress:totalByteSent/totalBytesExpectedToSend status:@"正在上传图片"];
                
                //                float progress = 0.0f;
                //                progress=totalByteSent/totalBytesExpectedToSend;
                //                [MBProgressHUD HUDForView:self.view].progress = progress;
                //                if(progress==1.0f){
                //                    [hud hideAnimated:YES];
                //                }
                
            }
        });
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    OSSTask * putTask = [self.client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        NSLog(@"objectKey: %@", put.objectKey);
        if (!task.error) {
            NSString *url=[NSString stringWithFormat:@"http://%@.%@/%@.jpg",BUCKET_NAME,@"oss-cn-beijing.aliyuncs.com",ds];
            self.sfzUrl=url;
            [SVProgressHUD dismiss];
            NSLog(@"upload object success!");
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
}


#pragma mark 接口--提现
-(void)updateTiXian{
    [self showDialog];
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,@"amount":self.tiXianMoney.text,@"price":self.realMoney,@"cardnumber":self.cardNum.text,@"bankname":self.cardBank.text,@"realname":self.cardName.text,@"phone":self.tiXianInfo.phone,@"code":self.code.text};
    [KKMyHttp updateTiXianInfo:params success:^(id data) {
        [self toast:@"提现请求提交成功"];
        [self dismissDialog];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

#pragma mark 接口--提现信息
-(void)getTiXianInfo{
    [self showDialog];
    [KKMyHttp getTiXianInfoSuccess:^(id data) {
        self.tiXianInfo=data;
        [self initData];
        [self dismissDialog];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

@end
